package cron

import (
	"context"

	"code.bydev.io/cht/customer/kyc-stub.git/pkg/bybit/kyc/common/enums"
	"code.bydev.io/cht/customer/kyc_admin_service/internal/pkg/kycadminrepo/o_kyc_action_state"
	"code.bydev.io/cht/customer/kyc_admin_service/internal/pkg/kycprovider"
	kpdto "code.bydev.io/cht/customer/kyc_admin_service/internal/pkg/kycprovider/dto"
	"code.bydev.io/cht/customer/kyc_admin_service/internal/pkg/kycprovider/provider/onfido"
	"code.bydev.io/frameworks/byone/core/logc"
	"code.bydev.io/frameworks/byone/core/logx"
)

func (d *Domain) OnfidoActionImageHandler(ctx context.Context) error {
	logc.Infow(ctx, "OnfidoActionImageHandler begin")
	limit := 100
	startID, err := d.GetScannerStartID(ctx, KeyOnfidoCompensateStartID)
	if err != nil {
		logc.Errorw(ctx, "s.GetScanStartID error", logc.Field("err", err))
		return err
	}

	// 获取已通过审批 POI 记录
	approvedPOIRecords, err := d.adminRepo.GetOnfidoApprovedPOIRecords(ctx, startID, limit)
	if err != nil {
		logc.Errorw(ctx, "s.adminRepo.GetOnfidoApprovedPOIRecords error", logc.Field("err", err))
		return err
	}
	if len(approvedPOIRecords) == 0 {
		logc.Infow(ctx, "no filter records")
		return nil
	}
	logc.Infow(ctx, "s.adminRepo.GetOnfidoApprovedPOIRecords info", logc.Field("startID", startID))
	newStartID := startID
	for _, record := range approvedPOIRecords {
		logx.ContextWithFields(ctx, logx.Field("id", record.Id), logx.Field("idempotentId", record.IdempotentId))
		newStartID = record.Id
		images, errAct := d.adminRepo.GetRecordsByIdempotentID(ctx, record.IdempotentId)
		if errAct != nil {
			logc.Errorw(ctx, "s.adminRepo.GetActionByIdempotentID error", logc.Field("err", errAct))
			return errAct
		}
		if len(images) > 0 {
			_ = d.SetScannerStartID(ctx, KeyOnfidoCompensateStartID, newStartID)
			continue
		}
		// 查找证件照+人脸照
		actionImgs, errImgs := d.GetOnfidoImagesByOldModel(ctx, record)
		if errImgs != nil {
			logc.Errorw(ctx, "s.GetOnfidoImagesByOldModel error", logc.Field("err", errImgs))
			return errImgs
		}
		if len(actionImgs) == 0 {
			_ = d.SetScannerStartID(ctx, KeyOnfidoCompensateStartID, newStartID)
			logc.Warnw(ctx, "OnfidoImgCompensateWarning", logc.Field("result", "failed"))
			continue
		}
		errCrt := d.adminRepo.CreateActionImages(ctx, nil, actionImgs)
		if errCrt != nil {
			logc.Errorw(ctx, "s.adminRepo.CreateActionImages error", logc.Field("err", errCrt))
			return errCrt
		}
		_ = d.SetScannerStartID(ctx, KeyOnfidoCompensateStartID, newStartID)
	}
	logc.Infow(ctx, "ActionImageHandler end")
	return nil
}

func (d *Domain) GetOnfidoImagesByOldModel(ctx context.Context, actState *o_kyc_action_state.Record) ([]*kpdto.KYCActionImage, error) {
	logc.Infow(ctx, "GetOnfidoImagesByOldModel begin", logc.Field("idempotentID", actState.IdempotentId))

	var actionImgs []*kpdto.KYCActionImage
	onfidoProvider := kycprovider.NewProvider(d.logger, kpdto.ProviderOnfido, d.teller).(*onfido.OnfidoProvider)
	livePhoto, errPhoto := onfidoProvider.GetLatestLivePhotoByOldModel(ctx, actState.AccountId)
	if errPhoto != nil {
		logc.Errorw(ctx, "onfidoProvider.GetLatestLivePhotoByOldModel error", logc.Field("err", errPhoto))
		return actionImgs, errPhoto
	}
	if livePhoto != nil {
		actionImgs = append(actionImgs, &kpdto.KYCActionImage{
			IdempotentID: actState.IdempotentId,
			MemberID:     actState.MemberId,
			Provider:     enums.KYCProvider_PROVIDER_ONFIDO,
			AccountID:    actState.AccountId,
			RecordID:     actState.RecordId,
			ImgID:        livePhoto.ID,
			ImgType:      kpdto.ImgTypeFace,
		})
	}

	docs, err := onfidoProvider.GetLatestPOIDocumentsByOldModel(ctx, actState.AccountId)
	if err != nil {
		logc.Errorw(ctx, "onfidoProvider.GetDocumentByOldModel error", logc.Field("err", err))
		return actionImgs, err
	}
	logc.Infow(ctx, "onfidoProvider.GetDocumentByOldModel info", logc.Field("docs", docs), logc.Field("actState.AccountId", actState.AccountId))
	if len(docs) > 0 {
		for _, docInfo := range docs {
			if docInfo == nil {
				continue
			}
			// POA 有时会没有 side 字段
			if docInfo.Side == "front" || docInfo.Side == "" {
				actionImgs = append(actionImgs, &kpdto.KYCActionImage{
					IdempotentID: actState.IdempotentId,
					MemberID:     actState.MemberId,
					Provider:     enums.KYCProvider_PROVIDER_ONFIDO,
					AccountID:    actState.AccountId,
					RecordID:     actState.RecordId,
					ImgID:        docInfo.ID,
					ImgType:      kpdto.ImgTypeDocFront,
				})
			} else {
				actionImgs = append(actionImgs, &kpdto.KYCActionImage{
					IdempotentID: actState.IdempotentId,
					MemberID:     actState.MemberId,
					Provider:     enums.KYCProvider_PROVIDER_ONFIDO,
					AccountID:    actState.AccountId,
					RecordID:     actState.RecordId,
					ImgID:        docInfo.ID,
					ImgType:      kpdto.ImgTypeDocBack,
				})
			}
		}
	}
	return actionImgs, nil
}
